#!/usr/bin/python
# -----------------------
# Import required Python libraries
# -----------------------
import time
import math
import RPi.GPIO as GPIO
import httplib,urllib;
# -----------------------
# Define some functions
# -----------------------

def measure():
  # This function measures a distance

  GPIO.output(GPIO_TRIGGER, True)
  time.sleep(0.00001)
  GPIO.output(GPIO_TRIGGER, False)
  start = time.time()
  stop = time.time()

  while GPIO.input(GPIO_ECHO)==0:
    start = time.time()

  while GPIO.input(GPIO_ECHO)==1:
    stop = time.time()

  elapsed = stop-start
  distance = (elapsed * 34300)/2

  return distance

def measure_average():
  # This function takes 3 measurements and
  # returns the average.

  distance1=measure()
  time.sleep(0.1)
  distance2=measure()
  time.sleep(0.1)
  distance3=measure()
  distance = distance1 + distance2 + distance3
  distance = distance / 3
  return distance

def sendData(val):
    params = urllib.urlencode({'params':'{"value":"'+str(val)+'"}'});
    print params;

    headers = {"Content-Type":"application/x-www-form-urlencoded",
           "Connection":"Keep-Alive","APIKey":"1a1aeed4941049238fd673bc320e5f4a","Referer":"http://api.machtalk.net/v1.0/device/a4465c44521e43a39fa0cca8672faa1b/1/1/datapoints/add"};
    conn = httplib.HTTPConnection("machtalk.net",10086)
    conn.request(method="POST",url="/v1.0/device/a4465c44521e43a39fa0cca8672faa1b/1/1/datapoints/add",body=params,headers=headers);
    response = conn.getresponse();
    print response.status
    if response.status == 302:
        print "!^_^!";
    else:
        print "\^0^/";
    conn.close();
# -----------------------
# Main Script
# -----------------------

# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)

# Define GPIO to use on Pi
GPIO_TRIGGER = 23
GPIO_ECHO    = 24

print "Ultrasonic Measurement"

# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
# Wrap main content in a try block so we can
# catch the user pressing CTRL-C and run the
# GPIO cleanup function. This will also prevent
# the user seeing lots of unnecessary error
# messages.
last_distance = 0
cur = time.time()
try:

  while True:

    distance = measure_average()
    print last_distance-distance
    print time.time()-cur
    if last_distance == 0:
        last_distance = distance

    if math.fabs(last_distance-distance) > 10 :
        last_distance = distance;
        sendData(last_distance);
    if time.time()-cur>200 :
        sendData(distance);
        cur = time.time()
    print "Distance : %.1f" % distance
    time.sleep(1)

except KeyboardInterrupt:
  # User pressed CTRL-C
  # Reset GPIO settings
  GPIO.cleanup()
